import 'package:dk_flutter_base/dk_core.dart';
import 'package:dk_flutter_base/dk_ui.dart';

///App中的Base界面
///* 该界面主要解决，当初次进入界面由于网络请求失败或者逻辑失败，导致没有返回建无法回退的情况
///* 该界面默认为Scaffold结构，只需要复写getAppBar
abstract class BaseScaffoldPage<B extends PageBloc> extends StatefulWidget {
  BaseScaffoldPage({Key key}) : super(key: key);

  @override
  State<BaseScaffoldPage> createState() {
    onCreateState();
    return _BaseScaffoldPageState<B>();
  }

  B getPageBloc();

  Key getProviderKey() {
    return null;
  }

  List<BlocProvider> getExtraBlocProviderList() {
    return null;
  }

  DkAppBar getAppBar(B pageBloc);

  DkScaffoldOption getScaffoldOption() {
    return null;
  }

  DkScaffoldOption configDefaultScaffoldOption(DkScaffoldOption option) {
    return option;
  }

  Widget configScaffold(DkScaffold dkScaffold) {
    return null;
  }

  void onCreateState() {}

  void onInitState(B pageBloc);

  void onBuild(B pageBloc) {}

  void onDispose(B pageBloc, {List<BlocProvider> blocProviderList}) {}
}

class _BaseScaffoldPageState<B extends PageBloc>
    extends State<BaseScaffoldPage<B>> {
  B pageBloc;
  List<BlocProvider> blocProviderList;

  @override
  void initState() {
    super.initState();
    pageBloc = widget.getPageBloc();
    blocProviderList =
        (widget.getExtraBlocProviderList() ?? List<BlocProvider>())
          ..add(BlocProvider<B>(
            builder: (context) => pageBloc,
          ));
    widget?.onInitState(pageBloc);
  }

  @override
  Widget build(BuildContext context) {
    pageBloc.context = context;
    widget.onBuild(pageBloc);
    return MultiBlocProvider(
      key: widget.getProviderKey(),
      providers: blocProviderList,
      child: getChild(),
    );
  }

  @override
  void dispose() {
    widget.onDispose(pageBloc, blocProviderList: blocProviderList);
    super.dispose();
  }

  Widget getChild() {
    DkScaffold scaffold = DkScaffold(
      widget.getScaffoldOption() ??
          widget.configDefaultScaffoldOption(
            DkScaffoldOption()
              ..dkAppBar = widget.getAppBar(pageBloc)
              ..body = BlocBuilder(
                bloc: pageBloc,
                builder: (BuildContext context, PageState state) {
                  if (state is PageBuildState) {
                    return state.pageBuilder(context);
                  }
                  return Container();
                },
              ),
          ),
    );
    return widget.configScaffold(scaffold) ?? scaffold;
  }
}
